﻿using System;
using System.Threading;

namespace ElectronicCommerce.Framework.Thread
{
    /// <summary>
    /// Represents an poll timer.
    /// </summary>
    public sealed class PollTimer : IDisposable
    {
        private Timer pollTimer;

        /// <summary>
        /// Start the polling process.
        /// </summary>
        /// <param name="callbackMethod">The method to callback when a cycle has completed.</param>
        /// <param name="pollCycleInMilliseconds">The time in milliseconds to poll.</param>
        public void StartPolling(TimerCallback callbackMethod, int pollCycleInMilliseconds)
        {
            if (callbackMethod == null)
            {
                throw new ArgumentNullException("callbackMethod");
            }

            if (pollCycleInMilliseconds <= 0)
            {
                throw new ArgumentException("Resources.InvalidPollCycleTime", "pollCycleInMilliseconds");
            }

            pollTimer = new Timer(callbackMethod, null, pollCycleInMilliseconds, pollCycleInMilliseconds);
        }

        /// <summary>
        /// Stop the polling process.
        /// </summary>
        public void StopPolling()
        {
            if (pollTimer == null)
            {
                throw new InvalidOperationException("Resources.InvalidPollingStopOperation");
            }

            pollTimer.Dispose();
            pollTimer = null;
        }

        void IDisposable.Dispose()
        {
            if (pollTimer != null) pollTimer.Dispose();
        }
    }
}
